import { useState } from "react";
import { useMount } from "react-use";
import type { ArticleView } from "../../apis/article";
import apis from "../../apis/article";

// 自定义hook，用于管理文章列表的数据逻辑
export default function useArticlesList() {
  const [articles, setArticles] = useState<ArticleView[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [nextCursor, setNextCursor] = useState<string | undefined>(undefined);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 加载文章列表
  const loadArticles = async (cursor?: string | undefined) => {
    if (!hasMore) {
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const result = await apis.articlesGet({ cursor, count: 10 });

      // 如果是第一次加载，则替换文章列表；否则追加到列表末尾
      if (!cursor) {
        setArticles(result.items);
      } else {
        setArticles((prevArticles) => [...prevArticles, ...result.items]);
      }

      setHasMore(result.hasMore);
      setNextCursor(result.nextCursor || undefined);
    } catch (err) {
      setError("获取文章列表失败，请稍后再试");
      console.error("Failed to load articles:", err);
    } finally {
      setLoading(false);
    }
  };

  // 首次加载文章列表
  useMount(() => {
    loadArticles();
  });

  // 加载更多文章
  const loadMore = () => {
    if (hasMore && !loading && nextCursor) {
      loadArticles(nextCursor);
    }
  };

  return {
    articles,
    loading,
    error,
    hasMore,
    loadMore,
  };
}
